﻿using Furion.DatabaseAccessor;

namespace iWare.Wms.WorkerService
{
    public class WorkerLog : BackgroundService
    {
        private readonly ILogger<WorkerLog> _logger;
        // 服务工厂
        private readonly IServiceScopeFactory _scopeFactory;

        public WorkerLog(ILogger<WorkerLog> logger,
                      IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        // 启动
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }

        // 执行逻辑
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            #region 清除日志
            while (!stoppingToken.IsCancellationRequested)
            {
                using (var scope = _scopeFactory.CreateScope())
                {
                    var services = scope.ServiceProvider;
                    // 获取仓储
                    var sysLogOp = Db.GetRepository<SysLogOp>(services);
                    var sysLogEx = Db.GetRepository<SysLogEx>(services);
                    var sysLogVis = Db.GetRepository<SysLogVis>(services);

                    //查询全部然后删除
                    var LogOp = sysLogOp.AsQueryable().ToList();
                    await sysLogOp.DeleteNowAsync(LogOp);

                    var LogEx = sysLogEx.AsQueryable().ToList();
                    await sysLogEx.DeleteNowAsync(LogEx);

                    var LogVis = sysLogVis.AsQueryable().ToList();
                    await sysLogVis.DeleteNowAsync(LogVis);

                    Console.WriteLine("1.执行清除日志");

                }
                //执行的方法
                await Task.Delay(60 * 60 * 1000, stoppingToken);
            }

            #endregion

        }

        // 停止
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}
